import Loading from '@/components/Loading';
import { api } from '@/utils/request/Api';
import { router } from 'expo-router';
import React, { useEffect, useState } from 'react';
import { Alert, StyleSheet, Text, TextInput, TouchableOpacity, View,Image,KeyboardAvoidingView,Platform } from 'react-native';
export default function ForgotScreen() {
    const [email, setEmail] = useState('');
    const [code, setCode] = useState('');
    const [times, setTimes] = useState(120);
    const [isCounting, setIsCounting] = useState(false);
    const [password, setPassword] = useState('');
    const [repassword, setRepassword] = useState('');
    const [loaded,setLoaded] = useState(false);
    const [token,setToken] = useState('');
    const [condition,setCondition] = useState(false);
    // 清除定时器
    useEffect(() => {
        return () => {
            if (isCounting) {
                clearInterval(window.countdownTimer);
                setIsCounting(false);
            }
        };
    }, [isCounting]);

    const onSubmit = () => {
        // 提交表单逻辑
        
        if(token == '' || token == null){
          Alert.alert('Tip','請求參數有錯誤');
          return;  
        }
        setLoaded(true);
        api.post(`auth/resetpwd?token=${token}`,{data:{password:password,repassword:repassword}}).then((res) => {
          setLoaded(false);
          if(res.code != 1){
              Alert.alert('Tip',res.msg);
              return false;
          }
          Alert.alert('Tip',"修改密碼成功，現在去登入",[
            {
              text: "OK",
              onPress: () => router.push('/'),
              style: "default",
            },
          ]);
        }).catch(()=>{setLoaded(false);})
    }
    // 提交验证二维码
    const onSubmitVaild = () => {
        if(!email || !code){
          Alert.alert('Tip','請輸入郵箱地址和驗證碼');
          return;
        }
        setLoaded(true);
        api.post("auth/vaildcode",{data:{email:email,event:"resetpwd",code:code}}).then((res) => {
            setLoaded(false);
            if(res.code != 1){
                Alert.alert('Tip',res.msg);
                return false;
            }
            setCondition(true);
            setToken(res.data.token);
        }).catch(()=>{setLoaded(false);})
    }
    /**
     * 獲取驗證碼
     */
    const getOriginCode = () => {
        if (!email) {
            Alert.alert('Tip','請輸入郵箱地址');
            return;
        }

        // 这里应该添加发送验证码的API调用
        setLoaded(true);
        setToken('');
        api.post("ems/send",{data:{email:email,event:"resetpwd"}}).then((res) => {
            setLoaded(false);
            if(res.code == 0){
              Alert.alert('Tip',res.msg);
              return false;
            }
            // 开始倒计时
            setIsCounting(true);
            let countdown = 120;
            setTimes(countdown);
            window.countdownTimer = setInterval(() => {
                countdown -= 1;
                setTimes(countdown);

                if (countdown <= 0) {
                    clearInterval(window.countdownTimer);
                    setIsCounting(false);
                }
            }, 1000);
            
        }).catch(()=>{setLoaded(false);})
        
    }
    if(condition){
        return (
          <KeyboardAvoidingView style={styles.container} behavior={Platform.OS == "ios" ? "padding" : "height"}>
            <Image source={require('../assets/logo.png')} style={styles.logo} />
            <Text style={styles.welcome}>修改密碼</Text>
            <Text style={styles.subText}>請輸入新的登入密碼</Text>
            <TextInput
                  style={styles.input}
                  placeholder="Enter new password"
                  value={password}
                  onChangeText={setPassword}
              />
              <TextInput
                  style={styles.input}
                  placeholder="Enter confirm password"
                  value={repassword}
                  onChangeText={setRepassword}
              />
              
              <TouchableOpacity
                  style={styles.loginBtn}
                  disabled={loaded}
                  onPress={onSubmit}
                  // onPress={() => router.push('/home')} // 可以改成你實際的 home 頁面路徑
                  >
                  <Text style={styles.loginText}>確認修改</Text>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => setCondition(false)}>
                  <Text style={styles.logintexts}>返回到上一步</Text>
              </TouchableOpacity>
               {loaded && <Loading />}
          </KeyboardAvoidingView>
        );
    }else{
      return (
        <KeyboardAvoidingView style={styles.container} behavior={Platform.OS == "ios" ? "padding" : "height"}>
            <Image source={require('../assets/logo.png')} style={styles.logo} />
                <Text style={styles.welcome}>找回密碼！</Text>
                <Text style={styles.subText}>請輸入您的郵箱地址，重新設置密碼</Text>
                <TextInput
                    style={styles.input}
                    placeholder="Enter email"
                    value={email}
                    onChangeText={setEmail}
                />
                <View style={styles.codeContainer}>
                    <TextInput
                        style={styles.codeinput}
                        placeholder="Enter code"
                        value={code}
                        onChangeText={setCode}
                    />
                    <View style={styles.sendbtn}>
                        <TouchableOpacity onPress={getOriginCode} disabled={isCounting}>
                            <Text style={[styles.forgot, isCounting ? {color: '#999'} : {}]}>
                                {isCounting ? `重新發送 (${times}s)` : '獲取驗證碼'}
                            </Text>
                        </TouchableOpacity>
                    </View>
                </View>
            
                <TouchableOpacity
                    style={styles.loginBtn}
                    disabled={loaded}
                    onPress={onSubmitVaild}
                    // onPress={() => router.push('/home')} // 可以改成你實際的 home 頁面路徑
                    >
                    <Text style={styles.loginText}>確認提交</Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => router.push('/')}>
                  <Text style={styles.logintexts}>現在去登入</Text>
              </TouchableOpacity>
                {loaded && <Loading />}
        </KeyboardAvoidingView>
      );
    }
  
}

const styles = StyleSheet.create({
    container: {
    flex: 1,
    padding: 24,
    justifyContent: 'center',
    backgroundColor: '#fff',
  },
  logo: {
    width: 80,
    height: 80,
    alignSelf: 'center',
    marginBottom: 20,
  },
  welcome: {
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 10,
  },
  subText: {
    textAlign: 'center',
    color: '#666',
    marginBottom: 30,
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderRadius: 10,
    marginBottom: 15,
  },
  forgot: {
    textAlign: 'center',
    color: '#007AFF',
    marginBottom: 15,
  },
  logintexts:{
    textAlign: 'center',
    paddingTop:20,
    color: '#007AFF',
    marginBottom: 20,
  },
  loginBtn: {
    backgroundColor: '#333',
    paddingVertical: 14,
    borderRadius: 10,
    alignItems: 'center',
  },
  loginText: {
    color: '#fff',
    fontSize: 18,
  },
  registerText: {
    marginTop: 30,
    textAlign: 'center',
    color: '#555',
  },
  codeContainer:{
    justifyContent: 'center',
    backgroundColor: '#fff',
    flexDirection: 'row',
  },
  codeinput:{
    flex:1,
    width:'50%',
    borderWidth: 1,
    borderColor: '#ccc',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderRadius: 10,
    marginBottom: 15,
  },
  sendbtn:{
    flex:1,
    width:'50%',
    paddingVertical: 14,
    alignItems: 'center',
    justifyContent: 'center',
  }
})